<script lang="ts" setup>
import type { TableInstanceColumns } from '@/components/ProTable/type'
import { OrderApi } from '@/apis'
import { useConfirm, useDictFilterOptions, useForm } from '@/hooks'
import { useTable } from '@/hooks/modules/useTable'
import { formatMoney } from '@/utils/common'
import { useDebounceFn } from '@vueuse/core'
import EndValidTimeEditModal from './components/EndValidTimeEditModal.vue'
import OrderStatus from './components/OrderStatus.vue'
import PayTypeEditModal from './components/PayTypeEditModal.vue'

defineOptions({
  name: 'OrderIndex',
})
const router = useRouter()

const { form } = useForm<OrderApi.OrderQuery>({
  orderId: undefined,
  payType: undefined,
  finAccountId: undefined,
  status: undefined,
  studentId: undefined,
  createDateFrom: undefined,
  createDateTo: undefined,
})

const statInfo = ref<OrderApi.OrderStatResp>()
const {
  tableData,
  loading,
  pagination,
  search,
} = useTable(pagination => OrderApi.getOrderPage({ ...form, ...pagination }), {
  onSuccess: async () => {
    statInfo.value = await OrderApi.getOrderStat(form)
  },
  immediate: false
})

const columns: TableInstanceColumns[] = [
  { title: '订单号', dataIndex: 'id', slotName: 'id', fixed: 'left', width: 210, summaryCellStyle: () => {
    return { backgroundColor: 'rgb(var(--arcoblue-6))', color: '#fff' }
  } },
  { title: '学生', dataIndex: 'student', slotName: 'student', width: 180 },
  { title: '购课班级', slotName: 'orderItem', align: 'center', width: 420 },
  { title: '总价', dataIndex: 'totalPrice', slotName: 'totalPrice', width: 130 },
  { title: '状态', dataIndex: 'status', slotName: 'status', align: 'center', width: 220, filterable: {
    filters: useDictFilterOptions('OrderStatusEnum'),
    multiple: true,
  } },
  { title: '支付方式', dataIndex: 'payType', slotName: 'payType', align: 'center', width: 110, filterable: {
    filters: useDictFilterOptions('PayTypeEnum'),
  } },
  { title: '收款账户', dataIndex: 'finAccountName', width: 120, render: ({ record }) => record.finAccount?.name || '-' },
  { title: '外部交易号', dataIndex: 'outTradeNo', slotName: 'outTradeNo', ellipsis: true, tooltip: true, width: 140 },
  { title: '退款', dataIndex: 'refundPrice', slotName: 'refundPrice', width: 120 },
  { title: '操作', slotName: 'action', width: 100, align: 'center', fixed: 'right' },
]

const tableSummary = ({ columns, data }) => {
  console.log('tableSummary')
  // statInfo.value = await OrderApi.getOrderStat(form)
  return [{
    id: '已支付合计',
    // totalPrice: ,
    totalPrice: null,
    student: `${statInfo.value?.totalOrderCount}笔，${formatMoney(statInfo.value?.totalOrderAmount)}`,
  }]
}

const spanMethod = ({ rowIndex, columnIndex }) => {
  if (rowIndex === 0 && columnIndex === 1) {
    return {
      colspan: 4,
    }
  }
}

// 创建
const onCreate = () => {
  router.push({ path: '/shop/enrollment/order/create' })
}

// 详情
const onDetail = (row) => {
  router.push({ path: '/shop/enrollment/order/detail', query: { id: row.id } })
}

// 筛选
const onFilterChange = (dataIndex, filteredValues) => {
  form[dataIndex] = filteredValues
}

// 班级详情
const toClassDetail = (row) => {
  router.push({ path: '/education/class/detail', query: { id: row.classId } })
}

// 修改订单有效期
const EndValidTimeEditRef = ref<InstanceType<typeof EndValidTimeEditModal>>()
const updateEndValidTime = (row) => {
  EndValidTimeEditRef.value?.open(row.id)
}

// 修改订单支付方式
const PayTypeEditModalRef = ref<InstanceType<typeof PayTypeEditModal>>()
const updatePayType = (row) => {
  PayTypeEditModalRef.value?.open(row)
}

const onCancelOrder = (row) => {
  useConfirm(() => OrderApi.cancelOrder(row.id), () => search(), {
    content: '是否确定取消该订单？',
    successTip: '取消成功',
    showModal: true,
  })
}

const debouncedSearch = useDebounceFn(() => search(), 100)

watch(() => form, () => {
  debouncedSearch()
}, {deep: true})

onMounted(() => {
  const route = useRoute()
  Object.assign(form, route.query)
})
</script>

<template>
  <ProPage title="报名订单" description="管理机构报名订单">
    <template #title-right>
      <div class="ml-88px flex">
        <StatisticsItem
          tip="今日新增" icon="count" unit="单" count-color="#00b42a"
          :count="`+${statInfo?.todayOrderCount || 0}`"
        />
        <StatisticsItem
          tip="订单总数" icon="count" unit="单" count-color="#ff7d00"
          :count="statInfo?.totalOrderCount || 0"
        />
        <StatisticsItem
          tip="订单总额" icon="count" unit="元" count-color="#ff7d00"
          :count="formatMoney(statInfo?.totalOrderAmount)"
        />
      </div>
    </template>
    <!-- <OrderRecentStatPanel /> -->
    <template #extra>
      <a-space>
        <a-button v-permission="['shop:order:manage']" type="primary" @click="onCreate">
          <template #icon>
            <icon-plus />
          </template>
          创建订单
        </a-button>
      </a-space>
    </template>
    <ProTable
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      :summary="false"
      :summary-span-method="spanMethod"
      @refresh="debouncedSearch"
      @filter-change="onFilterChange"
    >
    <template #search-panel>
      <a-space direction="vertical" size="small">
        <a-space wrap>
          <label class="label">筛选条件</label>
          <a-input v-model="form.orderId" placeholder="订单编号" allow-clear class="min-w-260px">
            <template #prefix>
              <icon-search />
            </template>
          </a-input>
          <StudentSelect v-model="form.studentId" class="min-w-260px" />
          <AccountSelect v-model="form.finAccountId" placeholder="收款账户" class="min-w-260px" />
        </a-space>
        <a-space wrap>
          <label class="label">订单时间</label>
          <RangePicker v-model:from="form.createDateFrom" v-model:to="form.createDateTo" :time="false" :placeholder="['创建时间-开始', '创建时间-结束']"/>
          <RangePicker v-model:from="form.payDateFrom" v-model:to="form.payDateTo" :time="false" :placeholder="['支付时间-开始', '支付时间-结束']"/>
        </a-space>
      </a-space>
      </template>
      <template #id="{ record }">
        <a-link @click="onDetail(record)">
          {{ record.id }}
        </a-link>
        <div class="pl-4px text-13px text-gray-5">
          {{ record.createTime }}
        </div>
      </template>
      <template #student="{ record }">
        <CellStudent :id="record.student.id" :name="record.student.name" :gender="record.student.gender" :phone="record.student.parentPhone" />
      </template>
      <template #orderItem="{ record }">
        <div v-for="(item, index) in record.orderItemList" :key="index" class="w-full flex-row-start-center">
          <a-tooltip :content="item.className">
            <a-tag class="mr-1 w-40px!" color="green" size="small">
              {{ item.lessonIndexes.length }}节
            </a-tag>
            <!-- <a-tag v-if="item.refundPrice" class="mr-1 w-1px!" color="red" size="small">
              -{{ formatMoney(item.refundPrice) }}
            </a-tag> -->
            <a-link class="px-0!" @click="toClassDetail(item)">
              <span class="w-348px truncate text-align-left">{{ item.className }}</span>
            </a-link>
          </a-tooltip>
        </div>
      </template>
      <template #totalPrice="{ record }">
        <div class="text-16px text-#ff7d00 font-600">
          {{ formatMoney(record.actualTotalPrice) }}
        </div>
        <div class="text-13px text-gray-5">
          原价:
          <span class="line-through">{{ formatMoney(record.originalTotalPrice) }}</span>
        </div>
      </template>
      <template #refundPrice="{ record }">
        {{ record.refundPrice ? formatMoney(record.refundPrice) : '-' }}
      </template>
      <template #status="{ record }">
        <OrderStatus :item="record" />
      </template>
      <template #payType="{ record }">
        <CellDict code="PayTypeEnum" :value="record.payType" :tag="false" />
      </template>
      <template #summary-cell="{ column, record, rowIndex }">
        <span> {{ record[column.dataIndex] }}</span>
      </template>
      <template #action="{ record }">
        <a-dropdown trigger="hover">
          <a-link>
            操作
            <icon-down />
          </a-link>
          <template #content>
            <a-doption
              v-permission="['shop:order:manage']"
              :disabled="record.status === 'PAID' || record.status === 'CANCELED'" @click="onCancelOrder(record)"
            >
              取消订单
            </a-doption>
            <a-doption
              v-permission="['shop:order:manage']"
              :disabled="record.status === 'PAID' || record.status === 'CANCELED'" @click="updateEndValidTime(record)"
            >
              修改过期时间
            </a-doption>
            <a-doption
              v-permission="['shop:order:pay-type-update']"
              :disabled="record.status !== 'PAID' || record.finAccountId === 'FUIOU'" @click="updatePayType(record)"
            >
              修改支付方式
            </a-doption>
          </template>
        </a-dropdown>
      </template>
    </ProTable>
    <EndValidTimeEditModal ref="EndValidTimeEditRef" @success="search" />
    <PayTypeEditModal ref="PayTypeEditModalRef" @success="search" />
  </ProPage>
</template>

<style lang="less" scoped>

.label {
  display: inline-block;
  width: 60px;
  text-align: right;
  flex-shrink: 0;
  margin-right: 10px;
}

.custom-filter {
  padding: 10px;
  background: var(--color-bg-5);
  border: 1px solid var(--color-neutral-3);
  border-radius: var(--border-radius-medium);
  box-shadow: 0 2px 5px rgb(0 0 0 / 10%);
}

.custom-filter-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}
</style>
